<?php

include_once("db.inc.php");
class DB
{
	private static $isPconnection 	= false;

	private static $usedConns 		= array();
	private static $usableConns 	= array();

	private static $arrConnConfig 	= array();

	public function DB()
	{
		global $ARR_GLOGAL_DB_CONFIG;
		
		DB::$arrConnConfig = $ARR_GLOGAL_DB_CONFIG;
	}

	public function getConnection($DBTag)
	{
		if(array_key_exists($DBTag, DB::$usableConns) && count(DB::$usableConns[$DBTag]) > 0){			
			$conn = array_pop(DB::$usableConns[$DBTag]);
			
			DB::$usedConns[$DBTag][]= $conn;
			
			return $conn;
		}else{			
			return $this->newConnection($DBTag);
		}
	}

	public function newConnection($DBTag)
	{
		$db_connect 	= DB::$isPconnection ? 'mysql_pconnect' : 'mysql_connect'; 
		$conResource 	= $db_connect(DB::$arrConnConfig[$DBTag]["host"], DB::$arrConnConfig[$DBTag]["user"], DB::$arrConnConfig[$DBTag]["pwd"], true); 
		
		if($conResource){
			mysql_select_db(DB::$arrConnConfig[$DBTag]["db"], $conResource);
			
			if(!empty(DB::$arrConnConfig[$DBTag]["encoding"])){
				$init_connect = "SET names " . DB::$arrConnConfig[$DBTag]["encoding"];
				mysql_query($init_connect, $conResource);
			}

			if(@mysql_error()) die('<b>error: connect database fail.</b> error : ' . mysql_error($conResource));

			if(array_key_exists($DBTag, DB::$usedConns)){
				$conns 		= DB::$usedConns[$DBTag];

				$conns[] 	= $conResource;
				
				DB::$usedConns[$DBTag] 	= $conns;
			}else{
				$conns 		= array();
				$conns[] 	= $conResource;
				
				DB::$usedConns[$DBTag] 	= $conns;
			}

			return $conResource;
		}else{
			return false;
		}
	}

	public function freeConnection($DBTag, $conn)
	{
		if(empty($conn) || empty($DBTag))
			return false;
			
		if(array_key_exists($DBTag, DB::$usedConns)){
			if(in_array($conn, DB::$usedConns[$DBTag])){				
				DB::$usedConns[$DBTag] = array_diff(DB::$usedConns[$DBTag], array($conn));
				
				if(count(DB::$usedConns[$DBTag]) == 0)
					unset(DB::$usedConns[$DBTag]);
					
				if(array_key_exists($DBTag, DB::$usableConns)){
					$conns 		= DB::$usableConns[$DBTag];
	
					$conns[] 	= $conn;
					DB::$usableConns[$DBTag] = $conns;
				}else{
					$conns 		= array();
					$conns[] 	= $conn;
					
					DB::$usableConns[$DBTag] = $conns;
				}		
				
				return true;
			}
		}else{ 
			return false;
		}
	}

	public function debug($DBTag)
	{
		echo "usedConns: " . count(DB::$usedConns[$DBTag]) . "\n";
		echo "usableConns: " . count(DB::$usableConns[$DBTag]) . "\n";
		
		echo "\n\n";
		
		print_r(DB::$usedConns);
		echo "\n";
		print_r(DB::$usableConns);
		
		echo "\n\n";
	}
}

?>
